<template>
  <div class="login-box">
    <transition name="fade">
      <div class="" v-if="isShow">
        <div class="login-title">
          <p>AUTOKEN</p>
        </div>

        <van-field
          v-model="form.username"
          center
          type="number"
          @change="uem=''"
          placeholder="请输入手机号"
          :error-message="uem"
          class="box-input"
        >
          <van-button
            slot="button"
            class="code-btn"
            size="small"
            v-if="hadSendCode"
            @click="getCode"
            :disabled="Code"
          >获取验证码</van-button>
          <van-button
            slot="button"
            class="code-btn"
            v-if="hadnotSendCode"
            :disabled="true"
            size="small"
            @click="getCode"
          >{{time}}秒</van-button>
        </van-field>

        <van-field
          v-model="phoneCode"
          class="box-input"
          placeholder="请输入验证码"
        />
        <van-field
          v-model="inviteId"
          @change="uem=''" placeholder="请输入邀请码"
          class="box-input"
        />
        <van-field
          v-model="form.password"
          @change="pem=''"
          :type="togglePassword?'text':'password'"
          placeholder="请输入密码"
          :error-message="pem"
          @click-icon="togglePassword=!togglePassword"
          class="box-input"
        >
          <img
            slot="icon"
            v-if="form.password"
            :src="togglePassword?'static/img/login-visible.png':'static/img/login-invisible.png'"
            style="width: 24px;"
          />
        </van-field>
        <van-field
          v-model="form.rePassword"
          @change="pem=''"
          style="margin-bottom: 20px;"
          :type="toggleRePassword?'text':'password'"
          placeholder="请确认密码"
          :error-message="pem"
          @click-icon="toggleRePassword=!toggleRePassword"
          class="box-input"
        >
          <img
            slot="icon"
            v-if="form.rePassword"
            :src="toggleRePassword?'static/img/login-visible.png':'static/img/login-invisible.png'"
            style="width: 24px;"
          />
        </van-field>
        <div class='loading-box'>
          <van-loading v-if="loadingControl" type="spinner" color="black" />
        </div>
        <van-button
          class="go-login"
          size="small"
          :disabled="logDis"
          @click="toLogin"
        >去登录</van-button>
        <div class="go-login" style="display:none">
          <span class="sweep" @click="clickScan">扫码注册</span>
          <div class="picupload" v-if="isIos">
            <van-uploader :after-read="onRead" result-type="text" accept="image/*" multiple>
            </van-uploader>
          </div>
          <input type="file" v-if="isAndroid" id="file" class="get-camera" @change="getImage" accept="image/*">
        </div>
        <van-button
          type="primary"
          size="large"
          :disabled="logDis"
          @click="login"
          class="loginBit"
        >注册</van-button>
      </div>
    </transition>
  </div>

</template>

<script>

  let scan = null;
  import { Toast,Loading } from 'vant';
  export default {
    data() {
      return {
        codeUrl: '',
        isShow: false,
        logDis:false,//登录按钮节流
        togglePassword: false,
        toggleRePassword: false,
        uem: "",
        hadSendCode:true,
        hadnotSendCode:false,
        pem: "",
        file:[],
        time:60,
        form: {
          username: '',
          password: '',
          rePassword: ''
        },
        loadingControl:false,
        inviteId:"",
        phoneCode:"",
        isIos:true,
        Code:false,
        isAndroid:true
      }
    },
    created() {

    },
    mounted() {
      console.log("最新版")
      if(this.andOrIos()) { //android
        this.isIos = false;
        this.isAndroid = true;
      }else{
        this.isIos = true;
        this.isAndroid = false;
      }
			this.inviteId = this.GetParam('userid');
      if(!this.inviteId){
       this.$router.push('/index')
      }else if(this.inviteId == "islogin"){
        this.inviteId = "";
      }else if(this.inviteId.indexOf('/') != -1){
        if(this.inviteId.indexOf('#') != -1){
          this.inviteId = this.inviteId.substr(0,this.inviteId.indexOf('#'))
        }
      }
      this.isShow = true;
			window.onload = () => {
			  document.addEventListener('touchstart', (event) => {
			    if (event.touches.length > 1) {
			       event.preventDefault();
			    }
			  }, { passive: false });

			  let lastTouchEnd = 0;
			  document.addEventListener('touchend', (event) => {
			    const now = (new Date()).getTime();
			    if (now - lastTouchEnd <= 300) {
			      event.preventDefault();
			    }
			    lastTouchEnd = now;
			  }, false);
			}
    },

    methods: {
      onRead(file) {
        var $this = this;
        if(file.length > 1){
          file.map(function(item,index){
            $this.file.push(item.file);
          })
        }else{
          $this.file.push(file.file);
        }
        let formData = new FormData();
        formData.append('img_file', $this.file[0]);
        $this.loadingControl = true;
        $this.$axios.post(url_g + "/qrdecode/",formData
        ).then((res)=>{
          $this.file = [];
          $this.loadingControl = false;
          if(res && res.data && res.data.content && res.data.content.indexOf('http') != -1){
            window.open(res.data.content)
          }else{
            this.toast =  Toast('请选择邀请的二维码图片');
          }
        }).catch((e)=>{
          $this.loadingControl = false;
          $this.file = [];
          this.toast =  Toast('请选择邀请的二维码图片');
        })
      },
      getImage(){
        var $this = this;
        let fileInput = document.getElementById('file')
        for(let i = 0; i < fileInput.files.length;i++){
          this.file.push(fileInput.files[i])
        }
        let formData = new FormData();
        formData.append('img_file', $this.file[0]);
        $this.loadingControl = true;
        $this.$axios.post(url_g + "/qrdecode/",formData
        ).then((res)=>{
          $this.file = [];
          $this.loadingControl = false;
          if(res && res.data && res.data.content && res.data.content.indexOf('http') != -1){
            window.open(res.data.content)
          }else{
            this.toast =  Toast('请选择邀请的二维码图片');
          }
        }).catch((e)=>{
          $this.loadingControl = false;
          $this.file = [];
          this.toast =  Toast('请选择邀请的二维码图片');
        })
      },
      GetParam(para){
        if(!location.href.split("?")[1]){
          return '';
        }
      	var paraArr = location.href.split("?")[1].substring(0).split('&');
        for(var i = 0;i < paraArr.length;i++){
            if(para == paraArr[i].split('=')[0]){
                return paraArr[i].split('=')[1];
            }
        }
        return '';
      },
      getCode(){
        var $this = this;
        if(this.form.username && (/^1\d{10}$/.test(this.form.username))){

          this.$axios({
            method: "POST",
            data: 'mobile='+this.form.username,
            url: url_g + "/verify/sms/"
          }).then((res) => {
            this.Code = true;
            this.hadSendCode = false;
            this.hadnotSendCode = true;
            var t = setInterval(function(){
              if($this.time == 0){
                $this.Code = false;
                $this.hadSendCode = true;
                $this.hadnotSendCode = false;
                clearInterval(t);
                $this.time = 60
              }else{
                $this.time = $this.time-1;
              }

            },1000)
          }).catch((e)=>{
            this.toast =  Toast('您输入的信息有误或网络有问题，请检查重试！');
          })
        }else{
          this.toast = Toast('请输入正确的手机号');
        }
      },
      login() {
        this.logDis = true;

        // 校验两次密码输入是否相同
        if(this.form.password !== this.form.rePassword ) {
          this.toast = Toast('请输入两次相同的密码！');
          return false;
        }

        if(this.form.username && this.form.password && this.phoneCode){
          if(!this.inviteId){
            this.toast = Toast('您需要被邀请才能注册');
            return false;
          }
          this.$axios({
            method: "POST",
            data: 'mobile='+this.form.username+'&password='+this.form.password+'&code='+this.phoneCode+'&reference='+this.inviteId,
            url: url_g + "/register/"
          }).then((res) => {
            this.logDis = false;
            console.log(res.data)
            sessionStorage.setItem("usermessage",JSON.stringify(res.data));
            token_g = JSON.parse(sessionStorage.getItem("usermessage")).token;
            this.$router.push('/index')
          }).catch((e)=>{
            this.logDis = false;
            if(e.response && e.response.data && e.response.data.detail){
              this.toast =  Toast(e.response.data.detail);
            }else{
              this.toast =  Toast('您输入的信息有误或网络有问题，请检查重试！');
            }
          })
        }else{
          this.logDis = false;
          this.toast = Toast('请输入完整信息');
        }

      },
      toLogin(){
        this.$router.push('/login')
      },
      clickScan() {

      },
      andOrIos() {
        let u = navigator.userAgent;
        let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
        let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        return isAndroid
      },
      //  判断手机来源
      ismobile(test){
        var u = navigator.userAgent, app = navigator.appVersion;
        if(/AppleWebKit.*Mobile/i.test(navigator.userAgent) || (/MIDP|SymbianOS|NOKIA|SAMSUNG|LG|NEC|TCL|Alcatel|BIRD|DBTEL|Dopod|PHILIPS|HAIER|LENOVO|MOT-|Nokia|SonyEricsson|SIE-|Amoi|ZTE/.test(navigator.userAgent))){
          if(window.location.href.indexOf("?mobile")<0){
            try{
              if(/iPhone|mac|iPod|iPad/i.test(navigator.userAgent)){
                return 1;
              }else{
                return 0;

              }
            }catch(e){
            }
          }
        }else if( u.indexOf('iPad') > -1){
          return 0;

        }else{
          return 1;
        }
      }
    }
  }
</script>

<style scoped="scoped">
  .loading-box{
    position:absolute;
    top: 35%;
    left: 46%;
  }
	.van-cell:not(:last-child)::after {
    border-bottom-width: 1px!important;
    border-color: #eee;
  }
	.get-camera{
    opacity:0;
    z-index:9999999;
    margin-top:30px;
    width:100px;
    margin-left:20px
	}
  .van-uploader {
    width: 100%;
    height: 100%;
    position: relative;
    display: inline-block;
  }
	.sweep{
    position: absolute;
    z-index: 0;
    width: 100px;
    text-align: center;
    /*background-color: #025596;*/
    /*border: 1px solid #025596;*/
    border-radius: 5px;
    color: #fff;
    height: 28px;
    line-height: 30px;
    font-size: 14px;
	}
  .login-box {
    height: 100vh;
    box-sizing: border-box;
    padding: 65px 40px 0;
    background: -moz-linear-gradient( top,#028aed,#273eec);
    background: -webkit-linear-gradient( top,#028aed,#273eec);
  }

  h3 {
    /*text-align: center;*/
    margin-bottom: 76px;
  }
  .fade-enter-active {
    -webkit-transition: all .5s;
    transition: all .5s;
  }
  .picupload{
    height: 30px;
    width: 100px;
  }
  .login-title {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-bottom: 60px;
  }
  .login-title p {
    color: #fff;
    font-size: 34px;
    margin: 0;
    line-height: 60px;
  }
  .login-title span {
    color: rgba(255,255,255,0.8);
    font-size: 14px;
  }
  .box-input {
    color: #fff;
    background-color: transparent;
  }
  .bottom-container {
    float: right;
  }
  .loginBit{
    background-color:#fff;
    border-radius:50px;
    border-width:0;
    color:#23accd;
    margin-top: 50px;
  }
  .go-login {
    background-color: transparent;
    font-size: 14px;
    float: right;
    border: 0;
    color: #fff;
    line-height:30px;
  }
  .code-btn {
    background-color: transparent;
    font-size: 12px;
    float: right;
    border: 1px solid #fff;
    color: #fff;
  }
</style>